const path = require('path')

const multer = require('@koa/multer')
const Jimp = require('jimp')
const { AVATAR_PATH, PICTURE_PATH } = require('../constants/file-path')

const avatarUpload = multer({
  dest: AVATAR_PATH
})

const pictureUpload = multer({
  dest: PICTURE_PATH
})

// single函数参数为form-data中的key
// 处理上传的文件时如果不指定文件名, 则multer会使用node内置模块crypto.randomBytes生成16字节的加密强伪随机数据作为文件名
const avatarHandler = avatarUpload.single('avatar')

const pictureHandler = pictureUpload.array('picture', 9)

const pictureResize = async (ctx, next) => {
  try {
    // @koa/multer 对multer做了一层处理，将ctx.req 赋给了 ctx.request
    const files = ctx.request.files
    for (const file of files) {
      const destPath = path.join(file.destination, file.filename)
      Jimp.read(file.path).then((image) => {
        image.resize(1280, Jimp.AUTO).write(`${destPath}-large`)
        image.resize(640, Jimp.AUTO).write(`${destPath}-middle`)
        image.resize(320, Jimp.AUTO).write(`${destPath}-small`)
      })
    }
  } catch (error) {
    console.log(error)
  }
  await next()
}

module.exports = {
  avatarHandler,
  pictureHandler,
  pictureResize
}
